from rest_framework import serializers
from apps.users.models import User
import re
from django_redis import get_redis_connection


class UserSerializer(serializers.Serializer):
    username = serializers.CharField()
    mobile = serializers.CharField()
    email = serializers.CharField()
    email_active = serializers.BooleanField()


class AddressSerializer(serializers.Serializer):
    id = serializers.IntegerField()

    # 外键序列化器的方式，需求不同方式不同
    # user_id = serializers.IntegerField()
    # PrimaryKeyRelatedField 和 read_only 或者 queryset 使用
    # user = serializers.PrimaryKeyRelatedField(read_only=True)
    user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all())

    # StringRelatedField 是调用 模型类里的 __str__ 方法  因为省市区返回的时候名字
    province = serializers.StringRelatedField()
    city = serializers.StringRelatedField()
    district = serializers.StringRelatedField()
    title = serializers.CharField()
    receiver = serializers.CharField()
    place = serializers.CharField()
    mobile = serializers.CharField()
    tel = serializers.CharField()
    email = serializers.CharField()


class RegisterModelSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(write_only=True)
    sms_code = serializers.CharField(write_only=True,max_length=6,min_length=6)
    allow = serializers.BooleanField(write_only=True)

    class Meta:
        model = User
        fields = ['username','password','password2','mobile','sms_code','allow']
        extra_kwargs = {
            'password':{
                'write_only':True
            }
        }

    def validate(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')
        password2 = attrs.get('password2')
        mobile = attrs.get('mobile')
        sms_code = attrs.get('sms_code')
        allow = attrs.get('allow')

        # username校验
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            raise serializers.ValidationError('username格式有误')

        # password检验
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            raise serializers.ValidationError('password格式有误')

        # password2 和 password
        if password != password2:
            raise serializers.ValidationError('两次输入不对')

        # mobile检验
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            raise serializers.ValidationError('mobile格式有误')

        #allow检验
        if allow != True:
            raise serializers.ValidationError('allow格式有误')

        # sms_code检验 (链接redis数据库)
        redis_conn = get_redis_connection('verify_code')

        # 从redis中取值
        sms_code_server = redis_conn.get('sms_%s' % mobile)

        # 判断该值是否存在
        if not sms_code_server:
            raise serializers.ValidationError('短信验证码过期')

        # 把redis中取得值和前端发的值对比
        if sms_code != sms_code_server.decode():
            raise serializers.ValidationError('短信验证码有误')

        del attrs['password2']
        del attrs['sms_code']
        del attrs['allow']

        return attrs

    def create(self, validated_data):
        return User.objects.create_user(**validated_data)